/* eslint-disable array-callback-return,no-undef */
import fetch from 'dva/fetch';
import React, { Component } from 'react';
import { Layout, Form, Modal, Spin, message, Avatar } from 'antd';
import styles from '../../../index.less';
import * as config from '../../../utils/config';
import * as commonFunc from '../../Common/commonFunc';
import baseHigher from '../../Common/baseHigher';
import PpopupPan from '../../../routes/ppopupPan/ppopupPan';
import Toolbar from '../../Common/ToolBar/ToolBar';
import TabMainTable from './TabMainTable';
import CheckModel from '../../Common/CheckModel';
import imgCheck from '../../../assets/haveChecked.png';
import imgInvalid from '../../../assets/haveCancel.png';

const { confirm } = Modal;
const { Header, Content } = Layout;

class CahfinancialAjust extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnData: config.btnData, /* 工具栏按钮 */
      masterConfig: { sId: '' }, // 主表 + 从表 配置
      sId: '', /* 业务数据ID */
      sActiveId: '', /* 窗体Id */
      disabled: false, /* 是否是查看状态 */
      loading: false,
      modalVisible: false, /* 弹窗显示状态 */
      modalPanel: {}, /* 弹窗面板属性 */
      mainTable: '', /* 主表 */
      tabRemarks: '', /* 备注 */
      financialData: {},
      gdsformconst: [], /* 常量 */
      visible: false, /* 审核不通过的弹窗 */
      sReturnMessage: [],
      sCheckModelId: '',
      sTabId: '', /* Tab页ID用于复制到等功能新弹出窗口避免弹出多个窗口 */
      newIdlength: 0, /* 复制到所用到的从表ID数 */
      newIdFlag: true, /* 页面复制数据后刷新渲染 */
      sListFormmasterId: '',
      sFormmasterId: '',
      configureMap: '',
      sFilterOrderBy: '',
      bFilter: '',
      currentData: [],
      pages: {},
      pageSize: '',
      iCountSum: '',
      formData: [],
      currentIndex: '',
      currentIndexFlag: false,
      selectStatus: false,
      count: 0, /* 从表总行数 */
      report: [], /* 打印报表 */
    };
  }


  componentWillMount() {
    this.setState({
      selectStatus: true,
    });
  }

  componentWillReceiveProps(nextProps) {
    const { dataList } = nextProps.content;
    const { gdsformconst, report } = nextProps;
    if (this.state.gdsformconst.length === 0) {
      this.setState({
        gdsformconst,
      });
    }
    if (this.state.report.length === 0) {
      const btnDataChild = [];
      report.forEach((child, i) => {
        btnDataChild.push({
          sName: `BtnPrint.${i}`,
          showName: child.sReportName,
          bVisible: true,
          sActiveId: '',
          sId: child.sId,
        });
      });
      this.setState({ btnDataChild, report });
    }
    /* 配置 */
    const {
      sDataListTabId, urlData, formRoute, loading, sId, paneType, checkedId, disabled, sParentId, newIds, sFilterOrderBy, bFilter, pageSize, pages, sListFormmasterId, currentData, newkey,
    } = dataList;
    if (urlData !== undefined && Object.keys(urlData).length > 0 && paneType !== undefined && paneType !== '' && nextProps.sTabId === sParentId) {
      const paneKey = new Date().getTime().toString();
      const pane = {
        copyToData: dataList.copyToData, /* 复制到数据 */
        title: urlData.sMenuName,
        route: urlData.sName,
        formId: urlData.sId,
        checkedId,
        disabled,
        key: paneKey,
        sFilterOrderBy,
        bFilter,
        pageSize,
        pages,
        sListFormmasterId,
        currentData,
        newkey,
      };
      this.props.onAddPane(pane);
      return;
    }
    /* 数据Id */
    const { formId } = nextProps;
    /* 窗体全部配置 */
    const masterConfig = commonFunc.getWindowConfig('cahfinancialadjust', nextProps.formData);
    /* 弹出窗数据返回,渲染数据并关闭弹出框 */
    if ((nextProps.app.ppopupPane !== undefined &&
      nextProps.app.ppopupPane.mainConfig !== undefined) ? (nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key
      && nextProps.formRoute === nextProps.app.ppopupPane.mainConfig.route) : false) {
      const { resultValue } = nextProps.app.ppopupPane;
      const { modalType } = nextProps.app.ppopupPane;
      /* 通用弹窗数据返值处理 */
      if ((resultValue !== undefined) && modalType === 'ppopup') {
        /* 数据集名 */
        const { dataName } = nextProps.app.ppopupPane;
        /* 数据集类型，对象型为Map 数组型为List */
        const { dataType } = nextProps.app.ppopupPane;
        const data = this.state[`${dataName}`];
        if (dataType === 'Map') {
          for (const key of Object.keys(resultValue)) {
            data[`${key}`] = resultValue[`${key}`];
          }
          this.setState({ [`${dataName}`]: data, modalVisible: false });
        }
        /* 弹出框关闭 */
        this.props.onRemoveModalPane({});
        return;
      }
    }
    if (nextProps.sTabId === sDataListTabId && nextProps.formRoute === formRoute && nextProps.formData.length > 0) {
      if (loading) {
        this.setState({ loading: true });
        return;
      }
      if (dataList.returnType !== undefined && dataList.returnType === 'CUD') {
        if (sId !== undefined && sId !== '') {
          this.setState({ sId });
        }
        this.setState({ disabled: dataList.disabled });
        this.handleRefresh(sId);
        return;
      }
      /* 窗体显示配置 */
      const masterShowConfig = commonFunc.getConfigCondition(masterConfig.gdsconfigformslave, 'bVisible');
      if (this.state.sActiveId === '') {
        const financialPan = nextProps.app.currentPane;
        /* 获取工具栏, 主表，页签标题 */
        this.setState({ toolProps: nextProps });
        const { formData } = urlData;
        /* 窗体配置 */
        const mainTable = formData.filter(item => (item.sTbName.toLowerCase() === 'cahfinancialadjust'))[0];
        /* 匹配主表 */
        this.setState({
          formData,
          mainTable,
          disabled: financialPan.disabled !== undefined ? financialPan.disabled : false,
          sId: financialPan.checkedId !== undefined ? financialPan.checkedId : '',
          sActiveId: formId,
          sFilterOrderBy: financialPan.sFilterOrderBy,
          bFilter: financialPan.bFilter,
          currentData: financialPan.currentData,
          sListFormmasterId: financialPan.sListFormmasterId,
          pageSize: financialPan.pageSize,
          pages: financialPan.pages,
          currentIndex: financialPan.newKey !== undefined ? financialPan.newKey.split('-')[financialPan.newKey.split('-').length - 1] : '',
        });
        if (financialPan.copyToData !== undefined) {
          const copyToData = JSON.parse(JSON.stringify(financialPan.copyToData));
          let masterData = {}; /* 主表数据 */
          let masterSlaveData = []; /* 第一个从表数据 */
          let newIdCount = 0;
          for (const value of Object.keys(copyToData)) {
            /* 是否数组 */
            if (!Array.isArray(copyToData[value])) {
              copyToData[value].sId = '';
              masterData = copyToData[value];
            } else {
              for (const v of copyToData[value]) {
                v.handleType = 'add';
                newIdCount += 1;
              }
              masterSlaveData = copyToData[value];
            }
          }
          this.setState({ financialData: masterData, subjectData: masterSlaveData, newIdlength: newIdCount });
        }
        this.setState({ masterConfig, masterShowConfig });
      } else if (dataList.returnType !== undefined && dataList.returnType === 'data') {
        const financialData = Object.keys(urlData).length > 0
          ? urlData[0] : {};
        const { bCheck } = financialData;
        let { selectStatus } = this.state;
        if (bCheck === true) {
          selectStatus = false;
        } else {
          selectStatus = true;
        }
        this.setState({
          selectStatus, financialData, loading: false, sTabId: nextProps.sTabId,
        });
      } else if (newIds !== undefined && newIds.length > 0) {
        const { subjectData } = this.state;
        const ids = newIds;
        for (const v of subjectData) {
          [v.sId] = ids;
          ids.splice(0, 1);
        }
        this.setState({ subjectData, newIdlength: 0, newIdFlag: false });
      }
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    let flag = true;
    /* 追加弹出框数值回填放行判断ppopupPane */
    if (nextProps.sTabId === nextProps.app.currentPane.key || ((nextProps.app.ppopupPane !== undefined
      && nextProps.app.ppopupPane.mainConfig !== undefined)
      ? nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key : false)) {
      if (nextState.disabled !== this.state.disabled) {
        return true;
      }
      flag = true;
    } else {
      flag = false;
    }
    return flag;
  }

  /* 刷新 */
  handleRefresh = (newsId) => {
    const { dispatch } = this.props;
    const { masterConfig, sId, sActiveId } = this.state;
    let id = sId;
    if (newsId !== undefined && newsId !== '') {
      id = newsId;
    }
    if (id !== undefined && id !== '') {
      /* 表Id */
      const mainId = masterConfig.sId;
      /* 业务数据Id */
      const value = { sId: id };
      const sTabId = this.props.app.currentPane.key;
      const mainDataUrl =
        `${config.server_host}business/getBusinessDataByFormcustomId/${mainId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: mainDataUrl,
          sTabId,
          componentName: 'cahfinancialadjust',
          value,
          formRoute: '/cahfinancialadjust',
          returnType: 'data',
        },
      });
    }
  };

  handlePrintChild = (sId) => {
    const { formData } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    const sMainTableId = formData[0].sId;
    const queryFilter = {};
    formData.map((item) => {
      const sDataId = item.sId;
      queryFilter[sDataId] = sDataId === sMainTableId ? { sId: this.state.sId } : {
        sSqlCondition: {
          sParentId: this.state.sId,
        },
      };
    });
    const sReportId = sId;
    const queryFilterJson = escape(JSON.stringify(queryFilter));
    const urlPrint = `${config.server_host}printReport/printPdf/${sReportId}?queryFilter=${queryFilterJson}&sModelsId=${sActiveId}&sMaintableId=${sMainTableId}&token=${encodeURIComponent(token)}`;
    window.open(urlPrint);
  };

  /* 获取上一条下一条首条末条 */
  handleSearchData = (sValue) => {
    const { sActiveId } = this.state;
    const { token } = this.props.app;
    const {
      sListFormmasterId, sFilterOrderBy, bFilter, formData, pages, pageSize, currentIndex, currentIndexFlag,
    } = this.state;
    let currentIndexPop = currentIndexFlag ? currentIndex : ((pages.pageNum - 1) * pageSize) + Number.parseInt(currentIndex, 10);
    if (sValue === 'first') {
      currentIndexPop = 1;
    } else if (sValue === 'end') {
      currentIndexPop = pages.totalCount;
    }
    const url = `${config.server_host}business/getBusinessDataByIndex?sModelsId=${sActiveId}`;
    const arrayForm = {};
    formData.forEach((child) => {
      const keys = child.sId;
      arrayForm[`${keys}`] = keys;
    });
    const value = {
      sClientType: '1',
      sListFormmasterId,
      sFormmasterId: formData[0].sId,
      currentPosition: currentIndexPop,
      configureMap: arrayForm,
      sHandleType: sValue,
      iCountSum: pages.totalCount,
    };
    if (bFilter !== undefined && bFilter !== '' && Object.keys(bFilter).length > 0) {
      value.push({ bFilter });
    }
    if (sFilterOrderBy !== undefined && sFilterOrderBy !== '' && Object.keys(sFilterOrderBy).length > 0) {
      value.push({ sFilterOrderBy });
    }
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const values = json.dataset.rows[0];
        const currentPostion = values.currentPosition;
        formData.forEach((child) => {
          const sMainId = child.sId;
          const sMainTableName = child.sTbName;
          if (sMainTableName === 'cahfinancialadjust') {
            this.setState({
              financialData: values[sMainId][0],
              sId: values[sMainId][0].sId,
            });
          }
        });
        this.setState({
          currentIndex: currentPostion,
          currentIndexFlag: true,
        });
      } else {
        message.error(json.msg);
      }
    });
  };
  /* 审核 */
  handleExamine = () => {
    const { sActiveId } = this.state;
    const { financialData, subjectData, gdsformconst } = this.state;
    const sToVoid = gdsformconst.filter(item => (item.sName === 'sToVoid'));
    if (financialData.bInvalid === true) {
      message.warning(sToVoid[0].showName);
      return;
    }
    const { token } = this.props.app;
    const url = `${config.server_host}business/doExamine?sModelsId=${sActiveId}`;
    const paramsMap = {
      iFlag: 1,
      iTmpCheck: 0,
      sFormGuid: sActiveId,
      sGuid: this.state.sId,
    };
    const value = {
      sClientType: '1',
      sProName: 'Sp_Calc_sStl',
      paramsMap,
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const { outData } = json.dataset.rows[0].dataSet;
        if (outData[0] === undefined || outData[0] === null || outData[0] === '' || outData[0].sReturn.split('-').length < 2) {
          const checksReturnArray = outData[0].sReturn.split('-');
          if (checksReturnArray[0] !== undefined && checksReturnArray[0] !== '') {
            financialData.bCheck = false;
            message.error(outData[0].sReturn);
          } else if (checksReturnArray[0] === undefined || checksReturnArray[0] === '') {
            financialData.bCheck = true;
            message.success(json.msg);
            /* 刷新commList页面数据 */
            if (this.props.app.currentPane.refresh) {
              this.props.app.currentPane.refresh();
            }
          }
          this.setState({ financialData, selectStatus: false });
        } else {
          const sReturnMessage = [];
          const sReturnArray = outData[0].sReturn.split('|');
          let sCheckModelId = '';
          if ((sReturnArray.length > 1) && ((sReturnArray[0].split('-')).length > 2)) {
            [sCheckModelId] = sReturnArray;
            [, sCheckModelId] = sCheckModelId.split('-');
          }
          sReturnArray.forEach((child) => {
            const smg = child.split('-');
            const sId = smg[0];
            const sData = subjectData.filter(item => (item.sId === sId));
            if (sData.length > 0) {
              const sNames = sData[0].sProductId.split('[-]');
              const sName = sNames.length > 2 ? sNames[1] : '';
              const messageCheck = `${sName}-${smg[2]}`;
              sReturnMessage.push(messageCheck);
              this.setState({
                sReturnMessage,
                sCheckModelId,
              });
            }
          });
          this.handleShowModal();
        }
      } else {
        message.error(json.msg);
      }
    });
  };

  /* 审核模板不通过时的弹窗 */
  handleShowModal = () => {
    this.setState({
      visible: true,
    });
  };
  /* 消审 */
  handleCancelExamine = () => {
    const { sActiveId } = this.state;
    const { financialData } = this.state;
    const { token } = this.props.app;
    const url = `${config.server_host}business/doExamine?sModelsId=${sActiveId}`;
    const paramsMap = {
      iFlag: 0,
      iTmpCheck: 0,
      sFormGuid: sActiveId,
      sGuid: this.state.sId,
    };
    const value = {
      sClientType: '1',
      sProName: 'Sp_Calc_sStl',
      paramsMap,
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const { outData } = json.dataset.rows[0].dataSet;
        if (outData[0] === undefined || outData[0] === null || outData[0] === '' || outData[0].sReturn.split('-').length < 2) {
          const checksReturnArray = outData[0].sReturn.split('-');
          if (checksReturnArray[0] !== undefined && checksReturnArray[0] !== '') {
            financialData.bCheck = true;
            message.error(outData[0].sReturn);
          } else if (checksReturnArray[0] === undefined || checksReturnArray[0] === '') {
            financialData.bCheck = false;
            message.success(json.msg);
            /* 刷新commList页面数据 */
            if (this.props.app.currentPane.refresh) {
              this.props.app.currentPane.refresh();
            }
          }
          this.setState({ financialData, selectStatus: true });
        }
      } else {
        message.error(json.msg);
      }
    });
  };
  /* 新增 */
  handleAdd= () => {
    /* Tab标签Id */
    this.setState({
      selectStatus: true,
      financialData: { bCheck: false, bInvalid: false },
      checkData: [],
      disabled: false,
      sId: '',
    });
  };
  /* 修改 */
  handleEdit = (obj) => {
    const { disabled } = obj;
    const { financialData, gdsformconst } = this.state;
    const sToVoidEdit = gdsformconst.filter(item => (item.sName === 'sToVoidEdit'));
    const sToExamineEdit = gdsformconst.filter(item => (item.sName === 'sToExamineEdit'));
    if (financialData.bInvalid === true) {
      message.warning(sToVoidEdit[0].showName);
      return;
    }
    if (financialData.bCheck === true) {
      message.warning(sToExamineEdit[0].showName);
      return;
    }
    this.setState({ disabled, selectStatus: true });
  };
  /* 删除 */
  handleDel = () => {
    const onhandleOk = this.handleOk;
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要删除?',
      onOk() {
        const value = {
          data: {
            sMasterTable: 'cahfinancialadjust',
            sId: [sId],
          },
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}business/delMasSlaBusinessData?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onhandleOk();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };

  handleInvalidOk = () => {
    const { financialData } = this.state;
    financialData.bInvalid = true;
    this.setState({
      financialData,
    });
    /* 刷新commList页面数据 */
    if (this.props.app.currentPane.refresh) {
      this.props.app.currentPane.refresh();
    }
  };

  /* 作废 */
  handleInvalid = () => {
    const onInvalidOk = this.handleInvalidOk;
    const { financialData, gdsformconst } = this.state;
    const sToExamineVoid = gdsformconst.filter(item => (item.sName === 'sToExamineVoid'));
    if (financialData.bCheck === true) {
      message.warning(sToExamineVoid[0].showName);
      return;
    }
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要作废?',
      onOk() {
        const value = {
          sTableName: 'cahfinancialadjust',
          sId: [sId],
          sHandleType: 'toVoid',
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}checkModel/updatebInvalid?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onInvalidOk();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };

  handleInvalidCancel = () => {
    const { financialData } = this.state;
    financialData.bInvalid = false;
    this.setState({
      financialData,
    });
    /* 刷新commList页面数据 */
    if (this.props.app.currentPane.refresh) {
      this.props.app.currentPane.refresh();
    }
  };
  /* 取消作废 */
  handleCancelInvalid = () => {
    const onInvalidCancel = this.handleInvalidCancel;
    const { financialData, gdsformconst } = this.state;
    const sToVoidExamine = gdsformconst.filter(item => (item.sName === 'sToVoidExamine'));
    if (financialData.bCheck === true) {
      message.warning(sToVoidExamine[0].showName);
      return;
    }
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要取消作废?',
      onOk() {
        const value = {
          sTableName: 'cahfinancialadjust',
          sId: [sId],
          sHandleType: 'cancel',
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}checkModel/updatebInvalid?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onInvalidCancel();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };
  /* 取消 */
  handleCancel =(type) => {
    const onhandleOk = this.handleOk;
    confirm({
      title: '确定要取消?',
      onOk() {
        onhandleOk(type);
      },
      onCancel() {},
    });
  };
  /* 非列表联动下拉 */
  handleSelectChange = (value, dataType, dataName) => {
    /* 数据集类型，对象型为Map 数组型为List */
    const data = this.state[`${dataName}`];
    if (dataType === 'Map') {
      for (const item of value) {
        data[`${item.key}`] = item.value;
      }
      this.setState({ [`${dataName}`]: data });
    }
  };
  /* 数据自动变更 */
  handleFormChange = (value) => {
    const key = Object.keys(value)[0];
    const { financialData, masterShowConfig } = this.state;
    const showConfig = masterShowConfig.filter(item => (item.sName === key))[0];
    if (showConfig !== undefined && showConfig.sDropDownType === 'sql') return;
    /* 数据处理,手动清空数据时数据会为undefined，不符合数据赋值要求 */
    const changeValue = commonFunc.changeValue(value);
    this.setState({
      financialData: { ...financialData, ...changeValue },
    });
  };
  /* 确认取消 */
  handleOk = () => {
    let lastIndex = -1;
    this.props.app.panes.forEach((pane, i) => {
      if (pane.key === this.props.app.currentPane.key) {
        lastIndex = i - 1;
      }
    });

    const panes = this.props.app.panes.filter(pane => pane.key !== this.props.app.currentPane.key);
    let currentPane;
    if (lastIndex >= 0) {
      currentPane = panes[lastIndex];
    } else if (lastIndex === -1 && panes.length > 0) {
      currentPane = panes[lastIndex + 1];
    } else {
      currentPane = { title: '', route: '', key: '0' };
    }
    this.props.onRemovePane(panes, currentPane);
    setTimeout(() => {
      /* 刷新commList页面数据 */
      if (this.props.app.currentPane.refresh) {
        this.props.app.currentPane.refresh();
      }
    });
  };
  /* 保存 */
  handleSubmit() {
    const { dispatch } = this.props;
    const { gdsformconst, financialData } = this.state;
    const sToExamineCheck = gdsformconst.filter(item => (item.sName === 'sToExamineCheck'));
    if (financialData.bCheck === true) {
      message.warning(sToExamineCheck[0].showName);
      return;
    }
    /* 业务数据Id */
    const sTabId = this.props.app.currentPane.key;
    this.form.validateFieldsAndScroll((err, formValue) => {
      if (!err) {
        const stateFormValue = this.state.financialData;
        const inputValue = { ...formValue, ...stateFormValue };
        const { sActiveId } = this.state;
        const dataUrl = `${config.server_host}business/addUpdateDelBusinessData?sModelsId=${sActiveId}`;
        if (this.state.sId !== '') {
          inputValue.handleType = 'update';
          inputValue.sFormId = sActiveId;
          const value = {
            data: [{
              sTable: 'cahfinancialadjust',
              column: [inputValue],
            }],
            sClientType: '1',
          };
          dispatch({
            type: 'content/getUrlPostData',
            payload: {
              url: dataUrl,
              sTabId,
              value,
              componentName: 'cahfinancialadjust',
              formRoute: '/cahfinancialadjust',
              returnType: 'CUD',
            },
          });
          setTimeout(() => {
            /* 刷新commList页面数据 */
            if (this.props.app.currentPane.refresh) {
              this.props.app.currentPane.refresh();
            }
          });
        } else {
          inputValue.handleType = 'add';
          const options = {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
          };
          const url = `${config.server_host}getUuid`;
          fetch(url, options).then(response => response.json()).then((json) => {
            if (json.code === 1) {
              const sId = json.dataset.rows[0];
              inputValue.sId = sId;
              /* 把新增时获取的唯一主键放在STATE中用于成功后刷新动作 */
              inputValue.maxBillNo = 'sBillNo';
              inputValue.sFormId = sActiveId;
              const value = {
                data: [{
                  sTable: 'cahfinancialadjust',
                  column: [inputValue],
                }],
                sClientType: '1',
              };
              dispatch({
                type: 'content/getUrlPostData',
                payload: {
                  url: dataUrl,
                  sTabId,
                  value,
                  componentName: 'cahfinancialadjust',
                  formRoute: '/cahfinancialadjust',
                  returnType: 'CUD',
                  sId,
                },
              });
            }
          });
        }
      }
    });
  }

  handleForm = (form) => {
    this.form = form;
  };

  /* 弹窗关闭 */
  handlePpopUpPaneCancel = () => {
    /* 弹窗类型，下拉/弹窗 */
    const { modalType } = this.props.app.ppopupPane;
    /* 数据集名 */
    const { dataName } = this.props.app.ppopupPane;
    const data = this.state[`${dataName}`];
    /* 如果为下拉新增则下拉值重置为空 */
    if (modalType === 'select') {
      /* 数据集类型，对象型为Map 数组型为List */
      const { dataType } = this.props.app.ppopupPane;
      const { mainKey } = this.props.app.ppopupPane;
      /* 窗体关闭时下拉重置为空,避免下拉项停留在NEW选项 */
      if (dataType === 'Map' && data[`${mainKey}`] === '000') {
        data[`${mainKey}`] = ' ';
      }
    }
    /* 置空models中弹窗面板 */
    this.props.onRemoveModalPane({});
    /* 隐藏弹窗面板 */
    this.setState({
      modalVisible: false,
      [`${dataName}`]: data,
    });
  };

  /* 弹窗面板状态更改 */
  handleModalPane = (value) => {
    this.setState({ modalVisible: value.modalVisible, modalPanel: value });
  };

  handleCopyTo = (activeId, value) => {
    const { financialData, gdsformconst } = this.state;
    const sToVoidCopy = gdsformconst.filter(item => (item.sName === 'sToVoidCopy'));
    const sToCopyLimit = gdsformconst.filter(item => (item.sName === 'sToCopyLimit'));
    const sToCheckCopy = gdsformconst.filter(item => (item.sName === 'sToCheckCopy'));
    if (financialData.bInvalid === true) {
      message.warning(sToVoidCopy[0].showName);
      return;
    }
    if (financialData.bCopyLimit === true) {
      message.warning(sToCopyLimit[0].showName);
      return;
    }
    if (financialData.bCheck === false) {
      message.warning(sToCheckCopy[0].showName);
      return;
    }
    const { dispatch } = this.props;
    const vConfig = value;
    /* 复制过去的主表数据 */
    let masterData = {};
    /* 复制过去的从表数据 */
    let masterSlaveData = [];
    if (vConfig.length > 0) {
      /* 过滤掉为了页面展示效果而存在的空数据 */
      const subjectData = this.state.subjectData.filter(item => (item.sId !== undefined && item.sId !== ''));
      const result = commonFunc.getBillCopyData(vConfig, this.state.financialData, subjectData);
      if (result !== undefined) {
        ({ masterData } = result);
        ({ masterSlaveData } = result);
      }
    }
    /* Tab标签Id */
    const paneKey = new Date().getTime().toString();
    /* 窗体Id */
    const sActiveId = activeId;
    const sNameUrl = `${config.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlData',
      payload: {
        url: sNameUrl, sTabId: paneKey, urlDataType: 'newPane', disabled: false, sParentId: this.state.sTabId, copyToData: { masterData, masterSlaveData },
      },
    });
  };

  render() {
    const { pageLoading } = this.props;
    const { props, state } = this;
    const { app } = props;
    const {
      visible, gdsformconst, sReturnMessage, sActiveId, sCheckModelId, financialData,
    } = this.state;
    const { loading } = this.state;
    return (
      <div>
        <Spin spinning={loading}>
          {pageLoading ? '' :
          <div>
            <CahfinancialAjustComponent
              {...props}
              {...state}
              handleSubmit={this.handleSubmit.bind(this)}
              handleEdit={this.handleEdit.bind(this)}
              handleAdd={this.handleAdd.bind(this)}
              handleCopyTo={this.handleCopyTo.bind(this)}
              handleOk={this.handleOk.bind(this)}
              handleCancel={this.handleCancel.bind(this)}
              handleRefresh={this.handleRefresh.bind(this)}
              handleDel={this.handleDel.bind(this)}
              onChange={this.handleFormChange.bind(this)}
              handleForm={this.handleForm.bind(this)}
              handleModalPane={this.handleModalPane.bind(this)}
              handleSelectChange={this.handleSelectChange.bind(this)}
              onExamine={this.handleExamine.bind(this)}
              onCancelExamine={this.handleCancelExamine.bind(this)}
              onInvalid={this.handleInvalid.bind(this)}
              onCancelInvalid={this.handleCancelInvalid.bind(this)}
              onNext={this.handleSearchData.bind(this, 'next')}
              onPrior={this.handleSearchData.bind(this, 'up')}
              onFirst={this.handleSearchData.bind(this, 'first')}
              onLast={this.handleSearchData.bind(this, 'end')}
              onPrintChild={this.handlePrintChild}
              onModalClose={this.handlePpopUpPaneCancel}
            />
            <CheckModel
              visible={visible}
              gdsformconst={gdsformconst}
              sReturnMessage={sReturnMessage}
              app={app}
              sActiveId={sActiveId}
              sCheckModelId={sCheckModelId}
              sTbName="cahfinancialadjust"
              sBillKey="Sp_Calc_sStl"
              sBillNo={financialData.sBillNo}
            />
            <Modal
              title={Object.keys(this.state.modalPanel).length > 0 ? this.state.modalPanel.title : ''}
              visible={this.state.modalVisible}
              onCancel={this.handlePpopUpPaneCancel.bind(this)}
              footer={null}
              width={1000}
              wrapClassName={styles.modal}
            >
              <div className={styles.popupPan} id="popupPan">
                <PpopupPan handleGetResult={this.handleGetResult} />
              </div>
            </Modal>
          </div>
          }
        </Spin>
      </div>
    );
  }
}

const CahfinancialAjustComponent = Form.create({
  mapPropsToFields(props) {
    const { financialData, masterShowConfig } = props;
    const obj = commonFunc.mapPropsToFieldsChangeValue(masterShowConfig, financialData, Form);
    return obj;
  },
  onValuesChange(props, changedFields) {
    props.onChange(changedFields);
  },
})((props) => {
  const { app, form } = props;
  const {
    sActiveId,
    masterConfig,
    sId,
    formData,
    dispatch,
    disabled,
    handleRefresh,
    handleEdit,
    handleCancel,
    handleSubmit,
    handleAdd,
    handleDel,
    changeDataFlag,
    handleModalPane,
    handleSelectChange,
    content,
    financialData,
    onInvalid,
    onCancelInvalid,
    onExamine,
    onCancelExamine,
    handleCopyTo,
    newIdlength,
    newIdFlag,
    onNext,
    onPrior,
    onFirst,
    onLast,
    btnDataChild,
    onPrintChild,
    selectStatus,
  } = props;
  /* 主表 */
  const { handleForm, onModalClose } = props;
  const onClose = onModalClose;
  const childProps = {
    app, form, sActiveId, sId, disabled, dispatch, content, masterConfig, handleModalPane, handleSelectChange, onClose,
  };
  const mainProps = {
    formData,
    componentName: 'cahfinancialadjust',
    ...childProps,
    changeDataFlag,
    dataName: 'financialData',
    dataType: 'Map',
    dataSet: financialData,
    newIdlength,
    newIdFlag,
  };
  const { bInvalid, bCheck } = financialData;
  const bShow = bInvalid || bCheck;
  let imgOption = '';
  if (bInvalid) {
    imgOption = <Avatar src={imgInvalid} />;
  } else if (bCheck) {
    imgOption = <Avatar src={imgCheck} />;
  }
  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar
            componentName="toolfinanciala"
            {...props}
            onAdd={handleAdd}
            onEdit={handleEdit}
            onBtnDel={handleDel}
            onBtnCancel={handleCancel}
            onRefresh={handleRefresh}
            onSubmit={handleSubmit}
            onBtnInvalid={onInvalid}
            onBtnCancelInvalid={onCancelInvalid}
            onBtnExamine={onExamine}
            onBtnCancelExamine={onCancelExamine}
            onCopyTo={handleCopyTo}
            onNext={onNext}
            onBtnPrior={onPrior}
            onBtnFirst={onFirst}
            onBtnLast={onLast}
            btnDataChild={btnDataChild}
            onBtnPrintChild={onPrintChild}
            bCheck={bCheck}
            selectStatus={selectStatus}
          >
            {handleForm(form)}
          </Toolbar>
        </Header>
        <Layout className={styles.clayout}>
          <Content className={styles.content}>
            <TabMainTable {...mainProps} />
            <div id="slaveTabs" className={bShow ? styles.bShow : ''}>
              <div style={{ display: bShow ? 'block' : 'none' }}>
                {imgOption}
              </div>
            </div>
          </Content>
        </Layout>
      </Layout>
    </Form>
  );
});


export default baseHigher(CahfinancialAjust);

